<template>
	<view class="page page-city">
		<uni-indexed-list :options="dataList" :showSelect="false" @click="bindClick"></uni-indexed-list>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				dataList: [],
				// 数据格式
				list: [
					{
						"letter": "A",
						"data": [
							{name: '阿克苏机场', id: '11'},
							{name: '阿拉山口机场', id: '22'}
						]
					},
					{
						"letter": "B",
						"data": [
							{name: '保山机场', id: '33'},
							{name: '包头机场', id: '44'}
						]
					}
				]
			}
		},
		onLoad: function(options) {
			// 城市列表
			this.$Http({
				url: 'city'
			}).then(res => {
				// 数组归纳为所需格式
				var arr = [], flag = 0, list = res.data;
				var obj = { letter: '', data: '' };
				for (var i = 0; i < list.length; i++) {
				    var index = '';
				    for (var j = 0; j < arr.length; j++) {
				        if (arr[j].letter == list[i]['first']) {
				            flag = 1;
				            index = j;
				            break;
				        }
				    }
				    if (flag == 1) {
				        var ele = arr[index];
				        ele.data.push({
							name: list[i]['shortname'],
							id: list[i]['id']
						});
				        flag = 0;
				    } else if (flag == 0) {
				        obj = {};
				        obj.letter = list[i]['first'];
				        obj.data = new Array();
				        obj.data.push({
							name: list[i]['shortname'],
							id: list[i]['id']
						});
				        arr.push(obj);
				    }
				}
				this.dataList = arr
			});
		},
		methods: {
			bindClick (e) {
				uni.$emit('chooseCity', e.item)
				// 关闭当前页面
				uni.navigateBack({ delta: 1 });
			}
		}
	}
</script>

<style lang="less">
	.page-city{position: relative;}
</style>
